package com.dinghui.ebookbag.module.middle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.dinghui.ebookbag.R;
import com.dinghui.ebookbag.config.Constants;
import com.dinghui.ebookbag.enity.ChildData;
import com.dinghui.ebookbag.enity.CurriculumCatalog;
import com.dinghui.ebookbag.enity.GroupData;
import com.dinghui.ebookbag.enity.Result;
import com.dinghui.ebookbag.enity.SpinnerItem;
import com.dinghui.ebookbag.enity.Subject;
import com.dinghui.ebookbag.enity.Version;
import com.dinghui.ebookbag.enity.VideoResource;
import com.dinghui.ebookbag.module.middle.adapter.CurriculumCatalogAdapter;
import com.dinghui.ebookbag.module.middle.adapter.CurriculumCatalogAdapter2;
import com.dinghui.ebookbag.module.middle.adapter.VideoResourceAdapter;
import com.dinghui.ebookbag.utils.OkHttpUtils;
import com.dinghui.ebookbag.utils.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import org.apache.commons.text.StringEscapeUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

// 同步课堂
public class SyncClassroomActivity extends AppCompatActivity implements View.OnClickListener {

    TextView leftBack;
    Spinner spSubject, spVersion, spVolume;

    private String subjectId = "";  // 科目id
    private String versionId = "";  // 版本id
    private String gradeId = "";    // 年级id
    private String volumeId = "";   // 册别id

    private ExpandableListView listView;
    private CurriculumCatalogAdapter2 adapter;

    private RecyclerView mRecyclerView;
    private VideoResourceAdapter mVideoResourceAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sync_classroom);
        ButterKnife.bind(this);
        ininView();
        initData();
    }

    private void ininView() {
        leftBack  = (TextView) findViewById(R.id.left_back);
        spSubject = (Spinner) findViewById(R.id.sp_subject);
        spVersion = (Spinner) findViewById(R.id.sp_version);
        spVolume  = (Spinner) findViewById(R.id.sp_volume);
        listView  = (ExpandableListView) findViewById(R.id.curriculum_catalog_elv);
        mRecyclerView = (RecyclerView) findViewById(R.id.video_list_rv);

        leftBack.setOnClickListener(this);
    }

    private void initData() {
        requestSubject();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_back: // 返回
                finish();
                break;
        }
    }

    // 获取学科
    private void requestSubject() {
        Map<String, Object> param = new HashMap<>();
        param.put("stageId", 3);

        OkHttpUtils.builder().url(Constants.API.SUBJECT).addParam("stageId", "3").post(false).async(new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                // 请求成功后的处理
                Gson gson = new Gson();
                List<Subject> subjectList = gson.fromJson(data, new TypeToken<List<Subject>>(){}.getType()); //把JSON格式的字符串转为List

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showSubjectData(subjectList);
                    }
                });
            }

            @Override
            public void onFailure(Call call, String errorMsg) {}
        });
    }

    private void showSubjectData(List<Subject> subjectList) {
        List<SpinnerItem> list = new ArrayList<SpinnerItem>();
        for (int i = 0; i < subjectList.size(); i++) {
            SpinnerItem spinnerItem=new SpinnerItem( subjectList.get(i).getId(), subjectList.get(i).getTitle());
            list.add(spinnerItem);
        }
        ArrayAdapter<SpinnerItem> adapter= new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice); //选中的样式 select_dialog_singlechoice simple_spinner_dropdown_item
        spSubject.setAdapter(adapter);

        //当选中某一个数据项时触发该方法
        /*
         * parent接收的是被选择的数据项所属的 Spinner对象，
         * view参数接收的是显示被选择的数据项的TextView对象
         * position接收的是被选择的数据项在适配器中的位置
         * id被选择的数据项的行号
         */
        spSubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //String value = spSubject.getSelectedItem().toString();//取value值则可以直接取
                //String value = ((SpinnerItem)spSubject.getSelectedItem()).getValue() ;
                subjectId = ((SpinnerItem)spSubject.getSelectedItem()).getID();
                Toast.makeText(SyncClassroomActivity.this, subjectId, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        requestVersion();
        /**/requestCatalog(subjectId, versionId, gradeId, volumeId);
    }

    // 获取版本
    private void requestVersion() {
        OkHttpUtils.builder().url(Constants.API.VERSION).post(false).async(new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                // 请求成功后的处理
                //Log.i(STORAGE_SERVICE, "-------onSuccess:---- " + data);

                try {
                    // 1.去掉前后多余的双引号
                    data = StringUtil.removeStartAndEndQuotationMarks(data);

                    // 2.去掉转义斜杠 \
                    // https://blog.csdn.net/u014295903/article/details/111831600
                    String s = StringEscapeUtils.unescapeJava(data);

                    // 3.使用fastjson解析json数据
//                    JSONObject jsonObject = JSON.parseObject(s);
//                    JSONArray jsonArray = jsonObject.getJSONArray("root");
//
//                    versionList = new ArrayList<>();
//                    versionList.add("请选择版本");
//                    for(int i=0;i<jsonArray.size();i++){
//                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                        String name = jsonObject1.getString("name");
//                        versionList.add(name);
//                    }

                    /**
                     * Gson解析
                     * https://blog.csdn.net/zy_281870667/article/details/41812627
                     * https://blog.csdn.net/weixin_30243533/article/details/96787259
                     */
                    Result result = new Gson().fromJson(s,Result.class);
                    List<Version> versionList = result.getRoot();

                   // Log.i(STORAGE_SERVICE, "-------versionList:---- " + versionList);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showVersionData(versionList);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {}
        });
    }

    private void showVersionData(List<Version>  versionList) {
        List<SpinnerItem> list = new ArrayList<SpinnerItem>();
        for (int i = 0; i < versionList.size(); i++) {
            SpinnerItem spinnerItem=new SpinnerItem( versionList.get(i).getId(), versionList.get(i).getName());
            list.add(spinnerItem);
        }
        ArrayAdapter<SpinnerItem> adapter= new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        spVersion.setAdapter(adapter);

        spVersion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                versionId = ((SpinnerItem)spVersion.getSelectedItem()).getID();
                Toast.makeText(SyncClassroomActivity.this, versionId, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        showVolumeData();
        requestCatalog(subjectId, versionId, gradeId, volumeId);
    }

    // 获取册别
    private void showVolumeData() {
        List<SpinnerItem> list = new ArrayList<SpinnerItem>();
        list.add(new SpinnerItem("31","31", "七年级上册"));  // volumeId:31  gradeId 31
        list.add(new SpinnerItem("31","32", "七年级下册"));  // volumeId:32  gradeId 31
        list.add(new SpinnerItem("31","33", "七年级全册"));  // volumeId:33  gradeId 31
        list.add(new SpinnerItem("32","31", "八年级上册"));  // volumeId:31  gradeId 32
        list.add(new SpinnerItem("32","32", "八年级下册"));  // volumeId:32  gradeId 32
        list.add(new SpinnerItem("32","33", "八年级全册"));  // volumeId:33  gradeId 32
        list.add(new SpinnerItem("33","31", "九年级上册"));  // volumeId:31  gradeId 33
        list.add(new SpinnerItem("33","32", "九年级下册"));  // volumeId:32  gradeId 33
        list.add(new SpinnerItem("33","33", "九年级全册"));  // volumeId:33  gradeId 33

        ArrayAdapter<SpinnerItem> adapter= new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        spVolume.setAdapter(adapter);

        spVolume.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                gradeId = ((SpinnerItem)spVolume.getSelectedItem()).getID();
                volumeId = ((SpinnerItem)spVolume.getSelectedItem()).getID2();

                Toast.makeText(SyncClassroomActivity.this, gradeId+ " --- " + volumeId, Toast.LENGTH_SHORT).show();

                requestCatalog(subjectId, versionId, gradeId, volumeId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    // 获取一级目录
    private void requestCatalog(String subjectId, String versionId, String gradeId, String volumeId) {
        OkHttpUtils.builder().url(Constants.API.CATALOG)
                .addParam("subjectId", subjectId)
                .addParam("versionId", versionId)
                .addParam("volumeId", volumeId)
                .addParam("gradeId", gradeId)
                .post(false)
                .async(new OkHttpUtils.ICallBack(){
            @Override
            public void onSuccessful(Call call, String data) {
                Log.i(STORAGE_SERVICE, "-------onSuccess:---- " + data);

                List<CurriculumCatalog> catalogList = new Gson().fromJson(data, new TypeToken<List<CurriculumCatalog>>(){}.getType());

                Log.i(STORAGE_SERVICE, "-------catalogs:---- " + catalogList);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       showCatalogData(catalogList);
                    }
                });
            }

            @Override
            public void onFailure(Call call, String errorMsg) {}
        });
    }

    private void showCatalogData(List<CurriculumCatalog> catalogList) {
        List<List<CurriculumCatalog>> childCatalogList = new ArrayList<>();
        for (int i = 0; i < catalogList.size(); i++) {
            List<CurriculumCatalog> children = catalogList.get(i).getChildren();
            childCatalogList.add(children);
        }
        adapter = new CurriculumCatalogAdapter2(this, catalogList, childCatalogList);
        listView.setAdapter(adapter);

        //重写OnGroupClickListener，实现当展开时，ExpandableListView不自动滚动
        /* listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                if (parent.isGroupExpanded(groupPosition)) {
                    parent.collapseGroup(groupPosition);
                } else {
                    //第二个参数false表示展开时是否触发默认滚动动画
                    parent.expandGroup(groupPosition, false);
                }
                //telling the listView we have handled the group click, and don't want the default actions.
                return true;
            }
        });*/

        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String catalogId = childCatalogList.get(groupPosition).get(childPosition).getId();
                requestVideoList(subjectId, versionId, gradeId, volumeId, catalogId);
                return true;
            }
        });
    }


    // 获取二级视频列表
    private void requestVideoList(String subjectId, String versionId, String gradeId, String volumeId, String catalogId) {
        OkHttpUtils.builder().url(Constants.API.VIDEO_LIST)
                .addParam("subjectId", subjectId)
                .addParam("versionId", versionId)
                .addParam("volumeId", volumeId)
                .addParam("gradeId", gradeId)
                .addParam("stageId", "3")
                .addParam("catalogId", catalogId)
                .addParam("page", "1")
                .addParam("size", "6")
                .post(false)
                .async(new OkHttpUtils.ICallBack(){
                    @Override
                    public void onSuccessful(Call call, String data) {
                        Log.i(STORAGE_SERVICE, "-------onSuccess:---- " + data);
                        try {
                            //JSONObject jsonObject = JSON.parseObject(data);
                            //JSONArray jsonArray = jsonObject.getJSONArray("list");

                            JSONObject jsonObject = new JSONObject(data);
                            Object object = jsonObject.get("list");
                            //JSONArray jsonArray = jsonObject.getJSONArray("list");
                            List<VideoResource> videoResourceList = new Gson().fromJson(object.toString(), new TypeToken<List<VideoResource>>(){}.getType());

                            Log.i(STORAGE_SERVICE, "-------jsonArray:---- " + videoResourceList);

                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   showVideoResourceData(videoResourceList);
                               }
                           });
                        } catch (org.json.JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call call, String errorMsg) {}
                });
    }

    private void showVideoResourceData(List<VideoResource> videoResourceList) {
        mVideoResourceAdapter = new VideoResourceAdapter(this, videoResourceList);
        mRecyclerView.setAdapter(mVideoResourceAdapter); //设置适配器

        //设置布局管理器 , 将布局设置成纵向
        LinearLayoutManager linerLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(linerLayoutManager);

        //设置分隔线
        //mRecycleView.addItemDecoration(new DividerItemDecoration(this , DividerItemDecoration.VERTICAL_LIST));

        //设置增加或删除条目动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        mVideoResourceAdapter.setOnItemClickListener(new VideoResourceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(SyncClassroomActivity.this,VideoPlayActivity.class);
                intent.putExtra("url", videoResourceList.get(position).getUrl());
                intent.putExtra("videoImage", videoResourceList.get(position).getVideoImage());
                startActivity(intent);
            }
        });
    }


}